package cn.tedu.vrd.filter;

import cn.tedu.vrd.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter" , urlPatterns = {"/insert.html","/product/delete","/admin.html"})
public class MyFilter implements Filter {
    /*init初始化方法*/
    public void init(FilterConfig config) throws ServletException {
    }
    //destroy销毁过滤器时执行的代码
    public void destroy() {
    }
    //此方法当客户端想服务器发出请求,并且这个请求被过滤器处理的话此方法执行
    //此方法中的doFilter方法执行 代表允许访问资源,
    // 不执行则代表禁止访问资源
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain ) throws ServletException, IOException {
        //将父类类型转成子类类型
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取Session对象
        HttpSession session = req.getSession();
        //取出登录成功时保存的用户对象
        User u = (User) session.getAttribute("u");
        if (u!=null){//登录过
            chain.doFilter(request, response);//放行
        }else{//未登录
            //重定向: 让客户端向指定的地址再次发出请求
            resp.sendRedirect("/login.html");
        }
    }
}
